<?php
    session_start();

    function get_rand_str($length = 4){
        $chars = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';//字符库
        $str = str_shuffle($chars);//随机打乱字符串
        $str=substr($str,0,$length);
        // 把所有字符转换为小写：
        return strtolower($str);
    }

    $width = 90;
    $height = 40;

    //新建一张彩色的图片
    $img = imagecreatetruecolor($width, $height);
    $backcolor = imagecolorallocate($img, 0 ,0 , 0);
    $textcolor = imagecolorallocate($img, 255, 255, 255);
    imagefilledrectangle($img, 0, 0, $width, $height, $backcolor);

    //获取随机数的方法
    $str = get_rand_str();

    $_SESSION['imagecode'] = $str;

    for($i = 0; $i < 500 ; $i++)
    {
        //生成x,y
        $x = mt_rand(0,$width);
        $y = mt_rand(0, $height);
        $color = imagecolorallocate($img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
        //写像素点上去
        imagesetpixel($img, $x, $y, $color);
    }

    imagettftext($img, 25, 0, 6, 30, $textcolor, "D:/phpstudy_pro/WWW/Web.end/Mysql/admin/assets/fonts/OpenSans-Light.ttf" , $str);
    //清空缓存
    ob_clean();

    header("Content-Type:image/png");

    imagepng($img);
    
    imagedestroy($img);
?>